package com.caine.multithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: CaineZhu
 * @Description: 所谓的线程复用逻辑, 实际上在串行执行任务的时候调用的是run不是start,
 * 因为start会做一系列的安全检查
 * @Date: Created in 17:45 2020/12/9
 * @Modified By:
 */
public class MyWorker implements Runnable {

    private Runnable runnable;

    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    public MyWorker() {
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        if (this.runnable == null) return;
        this.runnable.run();
    }


    public static void main(String[] args) {
        /**
         * 主要证明代码
         *  AbstractExecutorService->submit(Runnable task)>execute(ftask);
         *  ThreadPoolExecutor->execute(Runnable command)
         *      是否还有核心线程可创建> 是 > addWorker(command, true) >workers.add(w)>t.start(线程执行)
         *                           否 > if (isRunning(c) && workQueue.offer(command))放入队列
         *    Worker对象实现了runnable接口,run方法中有个while循环一直轮询workQueue获取队列中的任务,
         *    代码如下:while (task != null || (task = getTask()) != null)
         *    getTask本质就是从队列里获取任务 然后调用任务的run函数,刷新认知了有木有? 以前建议启动线程用start???
         */
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        executorService.submit(new Runnable() {
            @Override
            public void run() {

            }
        });

        MyWorker myWorker = new MyWorker();
        Thread t = new Thread(myWorker);
        myWorker.setRunnable(new Runnable() {
            @Override
            public void run() {
                System.out.println("1111111111111111");
            }
        });

        t.run();

        myWorker.setRunnable(new Runnable() {
            @Override
            public void run() {
                System.out.println("2222222");
            }
        });

        t.run();
    }

}
